//
//  ZDBInviteCodeDetailViewController.m
//  ZDB
//
//  Created by 微笑吧阳光 on 2020/3/30.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBInviteCodeDetailViewController.h"

@interface ZDBInviteCodeDetailViewController ()

@property (weak, nonatomic) IBOutlet UIView *codeBg;
@property (weak, nonatomic) IBOutlet UIImageView *codeImage;


@property (weak, nonatomic) IBOutlet UIButton *linkShareBtn;

@property (weak, nonatomic) IBOutlet UIButton *imageShareBtn;

@property(nonatomic,strong)UIImage * shareImage;

@property (weak, nonatomic) IBOutlet UIView *codeView;
@property (weak, nonatomic) IBOutlet UILabel *yaoqingmaLab;

@property (weak, nonatomic) IBOutlet UIButton *fenxiamaBtn;
@end

@implementation ZDBInviteCodeDetailViewController
- (void)viewWillAppear:(BOOL)animated
{
     [self statusBarStyleIsDark:NO];
     [self SetnavigationBarBackgroundImage:RGBA(255, 79, 42, 1) Alpha:1];
     [self SetNavigationBarTitleColor:[UIColor whiteColor]];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self statusBarStyleIsDark:YES];
    [self SetNavigationBarTitleColor:MAINTITLECOLOR];
    [self SetnavigationBarBackgroundImage:WHITECOLOR Alpha:1];
    [super viewWillDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    KViewRadius(self.codeView, 5);
    //self.webUrlStr =@"https://www.baidu.com";
    NSDictionary * userDicc =[[DJLoginHelper sharedInstance]cj_UserDicc];
    self.yaoqingmaLab.text = [NSString stringWithFormat:@"邀请码:%@",[userDicc jsonString:@"userCode"]];
    if (!kStringIsEmpty(self.webUrlStr)) {
        
        self.shareImage =[self createNonInterpolatedUIImageFormCIImage:[self creatQRcodeWithUrlstring:self.webUrlStr] withSize:150];
        self.codeImage.image=self.shareImage;
    }

    WEAKSELF
    [self.linkShareBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf);
        [JMNotifyView showNotify:@"邀请链接已复制到粘贴板" isSuccessful:YES];
        UIPasteboard * pastboard = [UIPasteboard generalPasteboard];
        pastboard.string = strongSelf.webUrlStr;
        
    }];
    
    [self.fenxiamaBtn add_BtnClickHandler:^(NSInteger tag) {
      //  STRONGSELFFor(weakSelf);
        [JMNotifyView showNotify:@"邀请码已复制到粘贴板" isSuccessful:YES];
        UIPasteboard * pastboard = [UIPasteboard generalPasteboard];
        pastboard.string = [userDicc jsonString:@"userCode"];
        
    }];
    
    
    
    [self.imageShareBtn add_BtnClickHandler:^(NSInteger tag) {
          STRONGSELFFor(weakSelf);
        //if (!strongSelf.shareImage) {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIImage * snapShotImage =[strongSelf getImageViewWithView:strongSelf.codeBg ];
                if (snapShotImage != nil) {
                     UIImageWriteToSavedPhotosAlbum(snapShotImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
                       
                   }
               /// [strongSelf loadImageFinished:shareImage];
                  });
       // }

      }];
    
}
- (UIImage *)getImageViewWithView:(UIView *)view{
    UIGraphicsBeginImageContext(view.frame.size);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage *image =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}
- (void)loadImageFinished:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}
 
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
    NSString *msg = nil ;
     if(error){
         msg = @"保存图片失败" ;
         [JMNotifyView showNotify:msg isSuccessful:NO];
     }else{
         msg = @"保存图片成功,可从相册选择发送给好友" ;
         [JMNotifyView showNotify:msg isSuccessful:YES];
     }
    
}

- (CIImage *)creatQRcodeWithUrlstring:(NSString *)urlString{
    
    // 1.实例化二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复滤镜的默认属性 (因为滤镜有可能保存上一次的属性)
    [filter setDefaults];
    // 3.将字符串转换成NSdata
    NSData *data  = [urlString dataUsingEncoding:NSUTF8StringEncoding];
    // 4.通过KVO设置滤镜, 传入data, 将来滤镜就知道要通过传入的数据生成二维码
    [filter setValue:data forKey:@"inputMessage"];
    // 5.生成二维码
    CIImage *outputImage = [filter outputImage];
    return outputImage;
}
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
